package vip.xiaonuo.xinmiao.core.handler;

import lombok.SneakyThrows;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.init.DatabasePopulatorUtils;
import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.io.IOException;

@Component
public class SqlImporter implements CommandLineRunner {

    private final JdbcTemplate jdbcTemplate;

    @javax.annotation.Resource
    private DataSource dataSource;

    public SqlImporter(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    @Override
    public void run(String... args) throws Exception {
        // 扫描所有的SQL文件并导入
        importSQLFiles("classpath*:sql/*.sql");
    }

    private void importSQLFiles(String locationPattern) throws IOException {
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        Resource[] resources = resolver.getResources(locationPattern);

        for (Resource resource : resources) {
            initDataFromSql(resource);
        }
    }

    @SneakyThrows
    private void initDataFromSql(Resource sql){
        final ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
        populator.addScripts(sql);
        DatabasePopulatorUtils.execute(populator, dataSource);
    }

}
